package com.project.genesis.common.util;

import com.project.genesis.base.BaseEntity;
import com.project.genesis.common.constant.Constants;
import org.springframework.beans.BeanUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.time.LocalDateTime;
import java.util.List;

public class MethodUtils {
    
    public static String userId = null;
    public static void packageBaseInfoList(List listEntity, Boolean isInsert)
    {
        listEntity.forEach(item -> {
            packageBaseInfo(item,isInsert);
        });
    }

    /**
     * 包装基本更新信息
     * @param obj
     * @param isInsert
     */
    public static void packageBaseInfo(Object obj, Boolean isInsert){
        try {
            userId = HttpUtils.getRequestHeaderInfo(Constants.USER_ID);
            userId = (userId == null || "".equals(userId)) ? Constants.DEFAULT_USER_ID : userId;
        } catch (Exception e) {
            userId = Constants.DEFAULT_USER_ID;
        }
        BaseEntity baseEntity =new BaseEntity();
        if(isInsert)
        {
            baseEntity.setCreateOn(LocalDateTime.now());
            baseEntity.setCreateBy(Long.parseLong(userId));
        }
        baseEntity.setUpdateBy(Long.parseLong(userId));
        baseEntity.setUpdateOn(LocalDateTime.now());
        BeanUtils.copyProperties(baseEntity,obj);
    }

    /**
     * 判断对象属性值是否为空
     * object 对象
     * ignoreList 不需要判断字段列表
     * return true:判断字段集合有空值   false:判断字段集合没有空值
     * */
    public static boolean objCheckIsNull(Object object,List<String> ignoreList) {
        Class clazz = (Class) object.getClass(); // 得到类对象
        Field fields[] = clazz.getDeclaredFields(); // 得到所有属性
        boolean flag = false; //定义返回结果，默认为true
        for (Field field : fields) {
            field.setAccessible(true);
            Object fieldValue = null;
            try {
                fieldValue = field.get(object); //得到属性值
                Type fieldType = field.getGenericType();//得到属性类型
                String fieldName = field.getName(); // 得到属性名
                if(ignoreList!=null && ignoreList.contains(fieldName))
                {
                    continue;
                }
//                System.out.println("属性类型：" + fieldType + ",属性名：" + fieldName + ",属性值：" + fieldValue);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            if (fieldValue == null || (fieldValue.equals(""))) {
                flag = true;
                break;
            }
        }
        return flag;
    }
}
